/**
 * Prime
 *
 * @author      Mayton
 * @license     http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3
 */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

// 30.12.2013 - Mayton

// TODO: Refactor without IEEE 754
// TODO: Check for MAX_INT or MAX_DOUBLE possible limitations
// TODO: Unit testing...
inline int isqrt(int i){
	return (int)sqrt((double)i);
}


// This is a stuped brute-force prime-gen
// TODO: Improove with In-memory prime cache
int main(int argc,char **argv){
        if (argc>1){
		int maxprime = atoi(argv[1]);
		if (maxprime >= 2){
			printf("2\n");
			for(int i=3;i<=maxprime;i+=2){
				// TODO: Refactor with Bresenham's SQRT function
				int maxdiv = 1 + isqrt(i);
				int isPrime = 1;
				for(int j=3;j<maxdiv;j++){
					if (i % j == 0) {
						isPrime = 0;
						break;
					}
				}
				if (isPrime) printf("%i\n",i);
			}
		}
		return 0;
	} else {
		fprintf(stderr,"Prime Numbers Generator 1.0 of 30 dec 2013, by Mayton\n\nUsage: prime [N]\n\n");
		return 1;	
	}
	
}